/**
 * Project Name:emm-website
 * File Name:ChannelSendHttpMessageServiceImpl.java
 * Package Name:com.emm.yixun.website.service.channel
 * Date:2017年6月27日下午3:39:02
 * Copyright (c) 2017, http://www.yixuninfo.com All Rights Reserved.
 *
 */

package com.emm.yixun.customer.service.impl.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.service.ProjectBuildingService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.enums.TransStatusEnum;
import com.emm.yixun.common.model.enums.TransTypeEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.utils.HttpUtil;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.customer.service.channel.ChannelSendHttpMessageService;
import com.emm.yixun.system.service.MerchantServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.jws.WebService;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * ClassName:ChannelSendHttpMessageServiceImpl <br/>
 * Function: 推送交易状态给渠道 <br/>
 * Reason: ADD REASON. <br/>
 * Date: 2017年6月27日 下午3:39:02 <br/>
 * 
 * @author Administrator
 * @version
 * @since JDK 1.6
 * @see
 */

@Service("channelSendHttpMessageService")
@WebService(endpointInterface = "com.emm.yixun.customer.service.channel.ChannelSendHttpMessageService")
public class ChannelSendHttpMessageServiceImpl implements ChannelSendHttpMessageService {
    protected Logger logger = LoggerFactory.getLogger(ChannelSendHttpMessageServiceImpl.class);
    @Value("${channel.request_url}")
    private String channelRequestUrl;
    
    @Autowired
    private CustomerServiceFacade customerServiceFacade;
    
    @Autowired
    private MerchantServiceFacade merchantServiceFacade;
    @Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
    @Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
    @Autowired
	private SignedServiceFacade signedServiceFacade;
    @Autowired
	private ProjectRoomService projectRoomService;
    @Autowired
	private ProjectBuildingService projectBuildingService;

    @Override
    public void sendTransaction(Long transId, String transType, boolean retreatFlag) {
		try {
			String transStatus = "";
			String merchantId = "";
			long customerId = 0L;
			long roomId = 0L;
			String roomName = "";
			String buildingName = "未设置";
			BigDecimal calArea = BigDecimal.ZERO;
			BigDecimal totalAmount = BigDecimal.ZERO;
			if(TransTypeEnum.PAYDEPOSIT.getNo().equals(transType)){
				transStatus = TransStatusEnum.PAYDEPOSIT.getNo();
				if(retreatFlag){
					transStatus = TransStatusEnum.RETREAT.getNo();
				}

				Response<PayDeposit> payDepositRes = payDepositServiceFacade.findById(transId);
				if(null != payDepositRes && payDepositRes.isSuccess() && null != payDepositRes.getEntity()){
					merchantId = String.valueOf(payDepositRes.getEntity().getMerchantId());
					customerId = payDepositRes.getEntity().getCustomerId();
					//roomId = payDepositRes.getEntity().getRoomId();
					//calArea = payDepositRes.getEntity().getCalculateArea();
					//totalAmount = payDepositRes.getEntity().getPayDepositAmount();
				}
			}else if(TransTypeEnum.SUBSCRIBE.getNo().equals(transType)){
				transStatus = TransStatusEnum.SUBSCRIBE.getNo();
				if(retreatFlag){
					transStatus = TransStatusEnum.RETREAT.getNo();
				}
				Response<Subscribe> subscribeRes = subscribeServiceFacade.findById(transId);
				if(null != subscribeRes && subscribeRes.isSuccess() && null != subscribeRes.getEntity()){
					merchantId = String.valueOf(subscribeRes.getEntity().getMerchantId());
					customerId = subscribeRes.getEntity().getCustomerId();
					roomId = subscribeRes.getEntity().getRoomId();
					calArea = subscribeRes.getEntity().getCalculateArea();
					//totalAmount = subscribeRes.getEntity().getSubscribeAmount();
				}
			}else if(TransTypeEnum.SIGNED.getNo().equals(transType)){
				transStatus = TransStatusEnum.SIGNED.getNo();
				if(retreatFlag){
					transStatus = TransStatusEnum.RETREAT.getNo();
				}
				Response<Signed> signedRes = signedServiceFacade.findById(transId);
				if(null != signedRes && signedRes.isSuccess() && null != signedRes.getEntity()){
					merchantId = String.valueOf(signedRes.getEntity().getMerchantId());
					customerId = signedRes.getEntity().getCustomerId();
					roomId = signedRes.getEntity().getRoomId();
					calArea = signedRes.getEntity().getCalculateArea();
					totalAmount = signedRes.getEntity().getSignAmount();
				}
			}

			//验证当前商户是否需要推送渠道接口信息
			if(sendVaild(merchantId)){
				Response<Customer> response = customerServiceFacade.findById(customerId);
				if(response.isSuccess()&& null != response.getEntity() && null != response.getEntity().getRecommendedChannelId()){
					//楼栋,房号,计价面积,成交总额
					ProjectRoom roomRes = projectRoomService.selectById(roomId);
					if(null != roomRes){
						roomName = roomRes.getRoomName();
						ProjectBuilding buildingRes = projectBuildingService.selectById(roomRes.getBuildingId());
						if(null != buildingRes){
							buildingName = buildingRes.getBuildingName();
						}
					}

					Map<String, String> paramsMap = new HashMap<String, String>();
					paramsMap.put("recommendedChannelId", response.getEntity().getRecommendedChannelId());
					paramsMap.put("transStatus", transStatus);
					paramsMap.put("buildingName", buildingName);
					paramsMap.put("roomName", roomName);
					paramsMap.put("calArea", String.valueOf(calArea));
					paramsMap.put("totalAmount", String.valueOf(totalAmount));

					JSONObject params = new JSONObject();

					JSONObject data = new JSONObject();
					data.put("recommendedChannelId", response.getEntity().getRecommendedChannelId());
					data.put("transStatus", transStatus);
					data.put("buildingName", buildingName);
					data.put("roomName", roomName);
					data.put("calArea", String.valueOf(calArea));
					data.put("totalAmount", String.valueOf(totalAmount));

					params.put("params", data);

					logger.info("渠道接收地址: " + channelRequestUrl);
					logger.info("渠道接收内容: " + JSON.toJSONString(params));
					String result = HttpUtil.doPostUrl(channelRequestUrl, params, "UTF-8");
					logger.info("渠道接口返回信息:" + result);

				}else{
					logger.error("客户缺少报备Id");
				}

			}else{
				logger.info("当前商户" + merchantId + "不需要推送渠道信息");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("sendTransaction error: ", e);
		}

    }

    //是否推送接口
    public boolean sendVaild(String merchanrtId){
	 Response<Merchant> merchantResponse = merchantServiceFacade.findById(new Long(merchanrtId));
	 if(merchantResponse.isSuccess()&&merchantResponse.getEntity()!=null){
	     String information = merchantResponse.getEntity().getPhoneInformation();
	     com.alibaba.fastjson.JSONArray jsonArray = JSON.parseArray(information);
		for (int i = 0; i < jsonArray.size(); i++) {
		    JSONObject jsonObject = jsonArray.getJSONObject(i);
		    String type = jsonObject.getString("type");
		    String status = jsonObject.getString("status");
		    if("4".equals(type)&&"1".equals(status)){ //是否推送渠道
			return true;
		    }
		}
	 }
	
	return false;
   }
}